#include "ReactorTcpServer.hpp"
#include <memory>

const uint16_t PORT = 8080;

using namespace tcpServer;
using namespace std;

bool heandler(const Request &res, Response &resp)
{
#ifdef DEBUG
    std::cout << "处理请求" << std::endl;
#endif

    switch (res._op)
    {
    case '+':
        resp._result = res._x + res._y;
        break;
    case '-':
        resp._result = res._x - res._y;
        break;
    case '*':
        resp._result = res._x * res._y;
        break;
    case '/':
    {
        if (res._y == 0)
            resp._exitcode = DIV_ERRO;
        else
            resp._result = res._x / res._y;
    }
    break;
    case '%':
    {
        if (res._y == 0)
            resp._exitcode = MOD_ERRO;
        else
            resp._result = res._x % res._y;
    }
    break;
    default:
        resp._exitcode = OPERA_ERRO;
        break;
    }
    return true;
}

void calculate(shared_ptr<tcpServer::Connection> conn)
{
    std::string packge;
    while (recvPackge(conn->_inbuffer, &packge))
    {
        std::string text;
        if (!deLenth(packge, &text))
            return;

        Request req;
        if (!req.deserialize(text))
            return;

        Response resp;
        heandler(req, resp);

        std::string resp_masg;
        resp.serialize(&resp_masg);

        conn->_outbuffer += enLenth(resp_masg);
    }
    if (conn->_sender)
        conn->_sender(conn);
}

int main()
{
    std::unique_ptr<TcpServer> server(new TcpServer(calculate, PORT));

    server->initServer();
    server->Dispatch();

    return 0;
}